/*
 * Copyright (C) 2005-2008 Dmitri Maximovich <maxim@md.pp.ru>
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 */
if(!com) var com={};
if(!com.maximdim) com.maximdim={};
if(!com.maximdim.cc) com.maximdim.cc={};
if(!com.maximdim.cc.options) com.maximdim.cc.options={};

com.maximdim.cc.options = {

  onLoad: function() {
  	var list = document.getElementById("servers");
  	com.maximdim.cc.options.clear(list);

  	var servers = com.maximdim.cc.prefs.getServersAsArray();
  	for(var i = 0; i < servers.length; i++) {
  	  var server = servers[i];

	  var item = list.appendItem(server.name);
	  item.value = server.id;

	  var cellUrl = document.createElement("listcell");
	  cellUrl.setAttribute("label", server.url);
      item.appendChild(cellUrl);
  	}
  },

  // TODO: better?
  clear: function(list) {
  	var count = list.getRowCount();
  	for(var i = 0; i < count; i++) {
  	  list.removeItemAt(0);
  	}
  },

  onSave: function() {
  	//com.maximdim.cc.prefs.setString("a", ""+(new Date()));
  },

  onAddServerCommand: function() {
    window.openDialog("chrome://cc/content/addServer.xul", "", "centerscreen", null);
	// TODO: only if OK pressed
    com.maximdim.cc.options.onLoad();
  },

  onEditServerCommand: function() {
	var list = document.getElementById("servers");
	var selected = list.selectedItem;
	if (selected != null) {
      var id = selected.value;
      window.openDialog("chrome://cc/content/addServer.xul", "", "centerscreen", id);
      // TODO: only if OK pressed
      com.maximdim.cc.options.onLoad();
    }
  },

  onDeleteServerCommand: function() {
	var list = document.getElementById("servers");
	var selected = list.selectedItem;
	if (selected != null) {
      if (confirm("Are you sure you want to delete '"+selected.label+"'?")) {
        var id = selected.value;
        com.maximdim.cc.prefs.deleteServer(id);
	    com.maximdim.cc.options.onLoad();
	  }
	}
  }

}
